<?php
/**
 * 模板文件扫描器
 * Template File Scanner
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 模板文件扫描器类
 * Template File Scanner Class
 */
class WBW_Template_File_Scanner {
    
    /**
     * 主题目录
     */
    private $theme_dir;
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->theme_dir = get_template_directory();
    }
    
    /**
     * 获取所有模板文件
     * 
     * @return array 模板文件信息数组
     */
    public function get_template_files() {
        $template_files = array();
        
        // 核心WordPress模板
        $core_templates = $this->get_core_templates();
        $template_files = array_merge($template_files, $core_templates);
        
        // 页面模板
        $page_templates = $this->get_page_templates();
        $template_files = array_merge($template_files, $page_templates);
        
        // 功能文件
        $function_files = $this->get_function_files();
        $template_files = array_merge($template_files, $function_files);
        
        return $template_files;
    }
    
    /**
     * 获取核心WordPress模板
     * 
     * @return array 核心模板文件
     */
    public function get_core_templates() {
        $core_templates = array(
            'index.php' => array(
                'name' => '主页模板',
                'type' => 'core',
                'required' => true,
                'description' => 'WordPress主入口模板文件'
            ),
            'header.php' => array(
                'name' => '头部模板',
                'type' => 'core',
                'required' => true,
                'description' => '网站头部模板'
            ),
            'footer.php' => array(
                'name' => '底部模板',
                'type' => 'core',
                'required' => true,
                'description' => '网站底部模板'
            ),
            'functions.php' => array(
                'name' => '主题函数',
                'type' => 'core',
                'required' => true,
                'description' => '主题核心功能文件'
            ),
            'style.css' => array(
                'name' => '主题样式',
                'type' => 'style',
                'required' => true,
                'description' => '主题主样式文件'
            ),
            '404.php' => array(
                'name' => '404错误页面',
                'type' => 'core',
                'required' => false,
                'description' => '404错误页面模板'
            ),
            'front-page.php' => array(
                'name' => '首页模板',
                'type' => 'core',
                'required' => false,
                'description' => '网站首页模板'
            ),
            'single.php' => array(
                'name' => '单篇文章模板',
                'type' => 'core',
                'required' => false,
                'description' => '单篇文章显示模板'
            ),
            'page.php' => array(
                'name' => '页面模板',
                'type' => 'core',
                'required' => false,
                'description' => '静态页面模板'
            ),
            'archive.php' => array(
                'name' => '归档模板',
                'type' => 'core',
                'required' => false,
                'description' => '归档页面模板'
            ),
            'search.php' => array(
                'name' => '搜索结果模板',
                'type' => 'core',
                'required' => false,
                'description' => '搜索结果页面模板'
            )
        );
        
        return $this->build_file_info_array($core_templates);
    }
    
    /**
     * 获取页面模板
     * 
     * @return array 页面模板文件
     */
    public function get_page_templates() {
        $page_templates = array();
        
        // 首页模板变体
        $home_templates = array(
            'home-template-1.php' => array(
                'name' => '首页模板1 (经典布局)',
                'type' => 'page',
                'required' => false,
                'description' => '基于index.html的经典布局'
            ),
            'home-template-2.php' => array(
                'name' => '首页模板2 (现代布局)',
                'type' => 'page',
                'required' => false,
                'description' => '基于index2.html的现代布局'
            ),
            'home-template-3.php' => array(
                'name' => '首页模板3 (时尚布局)',
                'type' => 'page',
                'required' => false,
                'description' => '基于index3.html的时尚布局'
            )
        );
        
        $page_templates = array_merge($page_templates, $home_templates);
        
        // 扫描page-templates目录
        $page_templates_dir = $this->theme_dir . '/page-templates';
        if (is_dir($page_templates_dir)) {
            $page_template_files = $this->scan_directory($page_templates_dir, '*.php');
            foreach ($page_template_files as $file) {
                $relative_path = 'page-templates/' . basename($file);
                $page_templates[$relative_path] = array(
                    'name' => '页面模板: ' . basename($file, '.php'),
                    'type' => 'page',
                    'required' => false,
                    'description' => '自定义页面模板'
                );
            }
        }
        
        return $this->build_file_info_array($page_templates);
    }
    
    /**
     * 获取WooCommerce模板
     * 
     * @return array WooCommerce模板文件
     */
    public function get_woocommerce_templates() {
        $woo_templates = array(
            'woocommerce/archive-product.php' => array(
                'name' => 'WooCommerce商品列表',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '商品归档页面模板'
            ),
            'woocommerce/single-product.php' => array(
                'name' => 'WooCommerce单个产品',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '单个产品页面模板'
            ),
            'woocommerce/cart/cart.php' => array(
                'name' => 'WooCommerce购物车',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '购物车页面模板'
            ),
            'woocommerce/checkout/form-checkout.php' => array(
                'name' => 'WooCommerce结账页面',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '结账页面模板'
            ),
            'woocommerce/myaccount/my-account.php' => array(
                'name' => 'WooCommerce我的账户',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '用户账户页面模板'
            ),
            'woocommerce/order/order-details.php' => array(
                'name' => 'WooCommerce订单详情',
                'type' => 'woocommerce',
                'required' => false,
                'description' => '订单详情页面模板'
            )
        );
        
        // 扫描woocommerce目录下的所有PHP文件
        $woo_dir = $this->theme_dir . '/woocommerce';
        if (is_dir($woo_dir)) {
            $additional_woo_files = $this->scan_directory_recursive($woo_dir, '*.php');
            foreach ($additional_woo_files as $file) {
                $relative_path = str_replace($this->theme_dir . '/', '', $file);
                if (!isset($woo_templates[$relative_path])) {
                    $woo_templates[$relative_path] = array(
                        'name' => 'WooCommerce模板: ' . basename($file, '.php'),
                        'type' => 'woocommerce',
                        'required' => false,
                        'description' => 'WooCommerce自定义模板'
                    );
                }
            }
        }
        
        return $this->build_file_info_array($woo_templates);
    }
    
    /**
     * 获取功能文件
     * 
     * @return array 功能文件
     */
    public function get_function_files() {
        $function_files = array();
        
        // inc目录下的核心功能文件
        $core_inc_files = array(
            'inc/template-assets.php' => array(
                'name' => '资源加载管理',
                'type' => 'function',
                'required' => true,
                'description' => '主题资源（CSS/JS）加载管理'
            ),
            'inc/template-tags.php' => array(
                'name' => '模板标签',
                'type' => 'function',
                'required' => true,
                'description' => '自定义模板标签和函数'
            ),
            'inc/template-filter.php' => array(
                'name' => '模板过滤器',
                'type' => 'function',
                'required' => true,
                'description' => 'WordPress钩子和过滤器'
            ),
            'inc/template-shop.php' => array(
                'name' => 'WooCommerce功能',
                'type' => 'function',
                'required' => false,
                'description' => 'WooCommerce相关功能'
            ),
            'inc/style-integration.php' => array(
                'name' => '样式集成',
                'type' => 'function',
                'required' => true,
                'description' => '样式文件集成管理'
            ),
            'inc/woocommerce-config.php' => array(
                'name' => 'WooCommerce配置',
                'type' => 'function',
                'required' => false,
                'description' => 'WooCommerce配置管理'
            ),
            'inc/theme-testing.php' => array(
                'name' => '主题测试',
                'type' => 'function',
                'required' => false,
                'description' => '主题测试和验证功能'
            )
        );
        
        $function_files = array_merge($function_files, $core_inc_files);
        
        // 扫描inc目录下的所有PHP文件
        $inc_dir = $this->theme_dir . '/inc';
        if (is_dir($inc_dir)) {
            $inc_files = $this->scan_directory($inc_dir, '*.php');
            foreach ($inc_files as $file) {
                $relative_path = 'inc/' . basename($file);
                if (!isset($function_files[$relative_path])) {
                    $function_files[$relative_path] = array(
                        'name' => '功能文件: ' . basename($file, '.php'),
                        'type' => 'function',
                        'required' => false,
                        'description' => '主题功能文件'
                    );
                }
            }
        }
        
        return $this->build_file_info_array($function_files);
    }
    
    /**
     * 获取指定类型的文件
     * 
     * @param string $type 文件类型
     * @return array 文件列表
     */
    public function get_files_by_type($type) {
        $all_files = $this->get_template_files();
        $woo_files = $this->get_woocommerce_templates();
        $all_files = array_merge($all_files, $woo_files);
        
        return array_filter($all_files, function($file) use ($type) {
            return $file['type'] === $type;
        });
    }
    
    /**
     * 验证文件路径
     * 
     * @param string $path 文件路径
     * @return bool 是否有效
     */
    public function validate_file_path($path) {
        // 安全检查：确保路径在主题目录内
        $real_path = realpath($path);
        $theme_real_path = realpath($this->theme_dir);
        
        if (!$real_path || !$theme_real_path) {
            return false;
        }
        
        return strpos($real_path, $theme_real_path) === 0;
    }
    
    /**
     * 扫描目录
     * 
     * @param string $directory 目录路径
     * @param string $pattern 文件模式
     * @return array 文件列表
     */
    private function scan_directory($directory, $pattern = '*') {
        if (!is_dir($directory)) {
            return array();
        }
        
        $files = glob($directory . '/' . $pattern);
        return array_filter($files, 'is_file');
    }
    
    /**
     * 递归扫描目录
     * 
     * @param string $directory 目录路径
     * @param string $pattern 文件模式
     * @return array 文件列表
     */
    private function scan_directory_recursive($directory, $pattern = '*') {
        if (!is_dir($directory)) {
            return array();
        }
        
        $files = array();
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile() && fnmatch($pattern, $file->getFilename())) {
                $files[] = $file->getPathname();
            }
        }
        
        return $files;
    }
    
    /**
     * 构建文件信息数组
     * 
     * @param array $template_definitions 模板定义
     * @return array 文件信息数组
     */
    private function build_file_info_array($template_definitions) {
        $file_info = array();
        
        foreach ($template_definitions as $file_path => $info) {
            $full_path = $this->theme_dir . '/' . $file_path;
            $file_info[] = array(
                'path' => $full_path,
                'relative_path' => $file_path,
                'name' => $info['name'],
                'type' => $info['type'],
                'required' => $info['required'],
                'description' => $info['description'],
                'exists' => file_exists($full_path),
                'size' => file_exists($full_path) ? filesize($full_path) : 0,
                'modified' => file_exists($full_path) ? filemtime($full_path) : 0
            );
        }
        
        return $file_info;
    }
    
    /**
     * 获取文件统计信息
     * 
     * @return array 统计信息
     */
    public function get_file_statistics() {
        $all_files = $this->get_template_files();
        $woo_files = $this->get_woocommerce_templates();
        $all_files = array_merge($all_files, $woo_files);
        
        $stats = array(
            'total_files' => count($all_files),
            'existing_files' => 0,
            'missing_files' => 0,
            'required_missing' => 0,
            'file_types' => array(),
            'total_size' => 0
        );
        
        foreach ($all_files as $file) {
            if ($file['exists']) {
                $stats['existing_files']++;
                $stats['total_size'] += $file['size'];
            } else {
                $stats['missing_files']++;
                if ($file['required']) {
                    $stats['required_missing']++;
                }
            }
            
            if (!isset($stats['file_types'][$file['type']])) {
                $stats['file_types'][$file['type']] = 0;
            }
            $stats['file_types'][$file['type']]++;
        }
        
        return $stats;
    }
    
    /**
     * 搜索文件内容
     * 
     * @param string $search_term 搜索词
     * @param array $file_types 文件类型过滤
     * @return array 搜索结果
     */
    public function search_file_content($search_term, $file_types = array()) {
        $all_files = $this->get_template_files();
        $woo_files = $this->get_woocommerce_templates();
        $all_files = array_merge($all_files, $woo_files);
        
        $results = array();
        
        foreach ($all_files as $file) {
            if (!$file['exists']) {
                continue;
            }
            
            if (!empty($file_types) && !in_array($file['type'], $file_types)) {
                continue;
            }
            
            $content = file_get_contents($file['path']);
            if ($content === false) {
                continue;
            }
            
            $lines = explode("\n", $content);
            foreach ($lines as $line_num => $line) {
                if (stripos($line, $search_term) !== false) {
                    $results[] = array(
                        'file' => $file,
                        'line_number' => $line_num + 1,
                        'line_content' => trim($line),
                        'match_position' => stripos($line, $search_term)
                    );
                }
            }
        }
        
        return $results;
    }
}